/**
 * 
 */
package demo.dcs;

import demo.java.lang.management.jvm.AppTraceConfig;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author mandy.hu
 *
 */
public class SampleImpl2 implements Sampler{
    private AtomicLong count = new AtomicLong();
    private Long lastTime = -1L;

    public SampleImpl2(){
        lastTime = System.currentTimeMillis();
    }
    

    @Override
    public boolean isSample(){
        int baseNumber = AppTraceConfig.getLocalConfig().getSampBaseline();
        int modNumber = (int)(1/AppTraceConfig.getLocalConfig().getSampFrequency());
    	boolean isSample = true;
    	if (AppTraceConfig.getLocalConfig().getSampleSwitch()) {
			return isSample;
		}else {
			 long n = count.incrementAndGet();
		       
		       if(System.currentTimeMillis() - lastTime  <= 1000){
		           if(n > baseNumber){
		        	   int mod = getModNumber(n,modNumber);
		               n = n%mod;
		               if(n != 0){
		                   isSample = false;
		               }
		           }
		       }else{
		           count.getAndSet(0);
		           lastTime = System.currentTimeMillis();//
		       }
		}
        return isSample;
    }
    
    private Integer getModNumber(Long qps,Integer baseNumber) {
    	if (qps<=100) {
			return baseNumber;
		}else if (qps>100 && qps<=500) {
			return 20;
		}else if (qps>500 && qps<=1000) {
			return 50;
		}else if (qps>1000 && qps<=2000) {
			return 100;
		}else if (qps>2000 && qps<=5000) {
			return 200;
		}else if (qps > 5000 && qps<=10000) {
			return 500;
		} 
        return 1000;
		
	}

}

